<template>
  <div class="supplier-list">
    <el-card shadow="never" class="card-com">
      <div class="card-1">
        <searchPanel @refresh="getData('reset')">
          <template v-slot:search>
            <el-form :inline="true" :model="listSearch" class="demo-form-inline" label-width="120px">
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="供应商编码">
                    <el-input v-model="listSearch.condition.supplierCode" clearable placeholder="请输入供应商编码"
                      @keyup.enter.native="getData('search')" @clear="getData('search')" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="供应商类型">
                    <BlackSelect v-model="listSearch.condition.supplierType" :options="supplyerType"
                      @change="getData('search')"> </BlackSelect>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="供应商名称">
                    <el-input v-model="listSearch.condition.supplierName" clearable
                      @keyup.enter.native="getData('search')" @clear="getData('search')" placeholder="请输入供应商名称" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="" label-width="120px">
                    <el-button type="primary" @click="getData('search')">查询</el-button>
                    <el-button @click="getData('reset')">重置</el-button>
                  </el-form-item>

                </el-col>
              </el-row>

            </el-form>
          </template>
          <template v-slot:edit>
            <el-button v-permission="'SUPPLIER:CREATE-EDIT'" :icon="Plus" type="primary" title="新增供应商"
              @click="AddEditBtn('add')"></el-button>
            <DropItem v-model:table-prop="tableProp"></DropItem>
          </template>
        </searchPanel>
      </div>
      <div class="card-2">
        <OnlyTable ref="onlyTableRef" class="card-2" :tableProps="tableProp" :pageTotal="pageParams.total"
          @get-page="handPage" :tableData="pageParams.tableData" :tableHeight="pageParams.tableHeight"
          :loading="pageParams.loadIng">
          <template #handle="scope">

            <el-button v-permission="'SUPPLIER:CREATE-EDIT'" type="primary" size="small" link
              @click="AddEditBtn('edit', scope.row)">编辑</el-button>
            <el-button v-permission="'SUPPLIER:DELETE'" type="danger" size="small" link
              @click="delBtn(scope.row)">删除</el-button>
            <el-button type="primary" size="small" link @click="detailBtn(scope.row)"
              v-permission="'SUPPLIER:DETAIL'">详情</el-button>
          </template>
        </OnlyTable>
      </div>
    </el-card>
    <!-- 如何来直接该呢 -->
    <addAndEdit ref="addAndEditRef" @refresh="getData('reset')" @searchEdit="getData('search')"></addAndEdit>
    <detailVue ref="detailRef"></detailVue>
  </div>
</template>
<script setup lang="ts">
/************************************引入************************************************* */
import {
  reactive,
  onMounted,
  defineAsyncComponent,
  ref,
  nextTick,
  onUnmounted,
} from "vue";
import _ from "lodash"
import { storeToRefs } from "pinia";
import { Search, Plus, Bottom, Refresh } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import {
  supplierPageApiPost,
  supplierDetailApiGet,
  supplierDeleteApiDelete,
} from "@/api/userMangement";
import useInstance from "@/hooks/useInstance";
import { supplierListStore } from "./pageStore";
import OnlyTable from "@/components/Table/onlyTable.vue";
import { useEnumStore } from "@/store/enumeration"
import BlackSelect from "@/components/customSon/blackSelect.vue";
import DropItem from "@/components/customSon/dropItem.vue";
import mittBus from '@/utils/mitt';
/************************************数据************************************************* */

const { productType, isIsp, supplyerType } = useEnumStore()
const { detailData, tableProp } = storeToRefs(supplierListStore());
const { global } = useInstance();

const addAndEdit = defineAsyncComponent(
  () => import("./components/addEdit.vue")
);

const detailVue = defineAsyncComponent(() => import('./components/detail.vue'))
const onlyTableRef = ref()
const addAndEditRef = ref<{ show: (type: string, row?: any) => void }>();
const detailRef = ref<{ show: (type: string, row?: any) => void }>();
const listSearch = reactive({
  pageNum: 1,
  pageSize: 20,
  condition: {
    supplierType: null,
    supplierCode: null,
    supplierName: null,
  },
  orders: ["created_time desc"],
});
const pageParams = reactive({
  total: 0,
  loadIng: false,
  tableData: [],
  tableHeight: 500,
});
/************************************方法************************************************* */


const detailBtn = async (row: any) => {
  try {
    const res = await supplierDetailApiGet({ id: row.id });
    if (res.code != 20000) return;
    detailRef.value?.show("edit", res.data);
  } catch (error) {
    console.log(error);
  }
};
onMounted(async () => {
  await getData("search");

});


const handPage = (val: { pageNum: number; pageSize: number }) => {
  listSearch.pageNum = val.pageNum;
  listSearch.pageSize = val.pageSize;
  getData("search");
};
const getData = async (type: string) => {
  pageParams.loadIng = true;
  if (type === "reset") {
    onlyTableRef.value.initPagination()
    listSearch.pageNum = 1;
    listSearch.pageSize = 20;
    listSearch.condition.supplierType = null;
    listSearch.condition.supplierCode = null;
    listSearch.condition.supplierName = null;
  }
  try {
    const res = await supplierPageApiPost(listSearch);
    if (res.code == 20000) {
      pageParams.loadIng = false;
      pageParams.total = res.data.total;
      pageParams.tableData = res.data.records.map((item: any) => {
        return {
          ...item,
          supplierType: supplyerType[item.supplierType - 1]?.value,
          isp: isIsp[item.isp],
          extInfo: item.extInfo == "{}" ? "" : item.extInfo
        };
      });
    }
  } catch (error) {
    pageParams.loadIng = false;
  } finally {
    mittBus.emit('scrollUpdate')
  }
};

const AddEditBtn = async (type: string, row?: any) => {
  if (type === "add") {
    addAndEditRef.value?.show("add");
  } else {
    // const res = await
    const res = await supplierDetailApiGet({ id: row.id });
    if (res.code == 20000) {

      addAndEditRef.value?.show("edit", res.data);
    }
  }
};
const delBtn = async (row: any) => {
  const flag = await global.$myconfirm(`是否确定删除该数据？  ${row.supplierName}`);
  if (flag) {
    const res = await supplierDeleteApiDelete({ id: row.id });
    console.log(res.data);
    if (res.code == 20000) {
      ElMessage({
        type: "success",
        message: "数据删除成功",
      });
      getData("search");
    } else {
      ElMessage({
        type: "error",
        message: "数据删除失败",
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.supplier-list {
  height: calc(100vh - 70px);

  .card-com {
    display: flex;
    flex-direction: column;

    .card-2 {
      flex-grow: 1;
    }
  }
}
</style>
